Skip to main content

Prefer local variables to globals, attributes, and indexed values

JavaScript engines first look for variables within the local scope before extending their search to larger scopes. If the variable is an indexed value in an array, or an attribute in an associative array, it will first look for the parent array before it finds the contents.

This has implications when working with performance-critical code. Take for instance a common for loop:

var global_variable = 0; function foo(){
global_variable = 0;
for (var i=0; i<items.length; i++) {
global_variable += items[i];
}
}

For every iteration in for loop, the engine will lookup items, lookup the length attribute within items, lookup items again, lookup the value at index i of items, and then finally lookup global_variable, first trying the local scope before checking the global scope.

A performant rewrite of the above function is:

function foo(){
var local_variable = 0;
for (var i=0, li=items.length; i<li; i++) {
local_variable += items[i];
}
return local_variable; }

For every iteration in the rewritten for loop, the engine will lookup li, lookup items, lookup the value at index i, and lookup local_variable, this time only needing to check the local scope.